//
//  LoginViewController.m
//  WideHelp
//
//  Created by ENERGY on 2018/8/20.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "LoginViewController.h"

static int i = 29;

@interface LoginViewController ()
@property (nonatomic, strong)UIImageView * iconImg;
@property (nonatomic, strong)UITextField * phoneTextField;
@property (nonatomic, strong)UITextField * verificationCodeTextField;//验证码内容
@property (nonatomic, strong)UIButton * codeBtn;//发送验证码
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSTimer * timer;
- (void)test:(NSTimer *)timmer;
@end

@implementation LoginViewController(networking)
- (void)sendCodeMessage{
    NSDictionary * dic = @{
                           @"mobile":self.phoneTextField.text
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"user/sendMsg" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"msg"] isEqualToString:@"success"]) {
            self.codeBtn.enabled = NO;
            //初始化定时器
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(test:) userInfo:nil repeats:YES];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
- (void)phoneNumLogin{
    NSDictionary *parameters = @{
                                 @"loginname":self.phoneTextField.text,
//                                 @"loginname":@"13912345678",
                                 @"deviceMode":[self iphoneType],
                                 @"systenVersion":[[UIDevice currentDevice] systemVersion],
                                 @"isAndroid":@(2),
//                                 @"code":self.verificationCodeTextField.text
                                 @"code":@"8888"
                                 };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"user/loginPhone" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"msg"] isEqualToString:@"success"]) {
            if ([[NSString stringWithFormat:@"%@", responseObject[@"msg"]] isEqualToString:@"success"]) {
                [UserModel sharedInstanced].userID = [responseObject[@"list"] objectForKey:@"user_id"];
                [UserModel sharedInstanced].cookie = [responseObject[@"list"] objectForKey:@"cookie"];
                [self dismissViewControllerAnimated:YES completion:nil];
            }else{
                NSLog(@"登录失败");
                ShowMessage(responseObject[@"msg"]);
            }
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end

@implementation LoginViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登录";
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    //构造控件
    [self setUpViews];
    
}

- (void)setUpViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    //头
    UIView * headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = headerView;
    //头像
    __weak typeof (self)weakSelf = self;
    self.iconImg = [[UIImageView alloc] init];
    [self.iconImg sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@"head_login_icon"]];
    [headerView addSubview:self.iconImg];
    //手机号前缀
    UILabel * prefixPhoneLab = [[UILabel alloc] init];
    [self label:prefixPhoneLab withFont:DEF_FontSize_14 withText:@"+86" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:headerView withBGColor:[UIColor clearColor]];
    //手机号
    self.phoneTextField = [[UITextField alloc] init];
    self.phoneTextField.placeholder = @"请输入手机号";
    self.phoneTextField.font = DEF_FontSize_14;
    self.phoneTextField.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:self.phoneTextField];
    //分割线
    UIView * phoneBorderLine = [[UIView alloc] init];
    phoneBorderLine.backgroundColor = getColor(@"f7f7f7");
    [headerView addSubview:phoneBorderLine];
    //验证码标题
    UILabel * verificationCodeTitleLab = [[UILabel alloc] init];
    [self label:verificationCodeTitleLab withFont:DEF_FontSize_14 withText:@"验证码" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:headerView withBGColor:[UIColor clearColor]];
    //验证码竖线
    UIView * codeVerticalLine = [[UIView alloc] init];
    codeVerticalLine.backgroundColor = getColor(@"f7f7f7");
    [headerView addSubview:codeVerticalLine];
    //验证码内容
    self.verificationCodeTextField = [[UITextField alloc] init];
    self.verificationCodeTextField.placeholder = @"请输入验证码";
    self.verificationCodeTextField.font = DEF_FontSize_14;
    self.verificationCodeTextField.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:self.verificationCodeTextField];
    //分割线横线
    UIView * codeBorderLine = [[UIView alloc] init];
    codeBorderLine.backgroundColor = getColor(@"f7f7f7");
    [headerView addSubview:codeBorderLine];
    //验证码按钮
    UIButton * codeBtn = [[UIButton alloc] init];
    [self button:codeBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:headerView];
    [codeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    codeBtn.titleLabel.font = DEF_FontSize_14;
    [codeBtn addTarget:self action:@selector(codeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [codeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.codeBtn = codeBtn;
    //找不到验证码
    UILabel * findNoCodeLab = [[UILabel alloc] init];
    [self label:findNoCodeLab withFont:DEF_FontSize_12 withText:@"找不到验证码？请拨打客服电话" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:headerView withBGColor:[UIColor clearColor]];
    //客服电话
    UIButton * serveBtn = [[UIButton alloc] init];
    [self button:serveBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:headerView];
    [serveBtn setTitle:@"400-888-8888" forState:UIControlStateNormal];
    serveBtn.titleLabel.font = DEF_FontSize_12;
    [serveBtn setTitleColor:getColor(greenBGColor) forState:UIControlStateNormal];
    //登录按钮
    UIButton * loginBtn = [[UIButton alloc] init];
    [self button:loginBtn withBGColor:nil withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:4 withMasksToBounds:NO withViwe:headerView];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = DEF_FontSize_14;
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"maself_bg"] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //下面分割线
    UIView * bottomLine = [[UIView alloc] init];
    bottomLine.backgroundColor = getColor(@"f5f5f5");
    [headerView addSubview:bottomLine];
    //或
    UILabel * orLab = [[UILabel alloc] init];
    [self label:orLab withFont:DEF_FontSize_12 withText:@"或" withTextColor:getColor(@"9b9b9b") withTextAlignment:NSTextAlignmentCenter withView:headerView withBGColor:[UIColor whiteColor]];
    //微信图标
    UIButton * weChatBtn = [[UIButton alloc] init];
    [weChatBtn setImage:[UIImage imageNamed:@"weixin"] forState:UIControlStateNormal];
    [headerView addSubview:weChatBtn];
    //微信标题
    UILabel * weChatLab = [[UILabel alloc] init];
    [self label:weChatLab withFont:DEF_FontSize_12 withText:@"微信登录" withTextColor:getColor(@"9b9b9b") withTextAlignment:NSTextAlignmentCenter withView:headerView withBGColor:[UIColor clearColor]];
    //frame
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - TABBAR_HEIGHT);
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, weChatLab.bottom + 18/WIDTH_6_SCALE);
    self.iconImg.frame = CGRectMake(0, 57/WIDTH_6_SCALE, 70/WIDTH_6_SCALE, 70/WIDTH_6_SCALE);
    self.iconImg.centerX = headerView.centerX;
    prefixPhoneLab.frame = CGRectMake(16/WIDTH_6_SCALE, self.iconImg.bottom + 95/WIDTH_6_SCALE, 70/WIDTH_6_SCALE, 17/WIDTH_6_SCALE);
    self.phoneTextField.frame = CGRectMake(prefixPhoneLab.right, prefixPhoneLab.top, SCREEN_WIDTH - 32/WIDTH_6_SCALE - prefixPhoneLab.right, prefixPhoneLab.height);
    phoneBorderLine.frame = CGRectMake(15/WIDTH_6_SCALE, self.phoneTextField.bottom + 18/WIDTH_6_SCALE, SCREEN_WIDTH - 30/WIDTH_6_SCALE, 1/WIDTH_6_SCALE);
    verificationCodeTitleLab.frame = CGRectMake(prefixPhoneLab.left, phoneBorderLine.bottom + 18/WIDTH_6_SCALE, prefixPhoneLab.width, prefixPhoneLab.height);
    self.verificationCodeTextField.frame = CGRectMake(self.phoneTextField.left, verificationCodeTitleLab.top, 163/WIDTH_6_SCALE, self.phoneTextField.height);
    codeBorderLine.frame = CGRectMake(phoneBorderLine.left, self.verificationCodeTextField.bottom + 18/WIDTH_6_SCALE, phoneBorderLine.width, phoneBorderLine.height);
    codeVerticalLine.frame = CGRectMake(self.verificationCodeTextField.right, phoneBorderLine.bottom, 1/WIDTH_6_SCALE, codeBorderLine.top - phoneBorderLine.bottom);
    codeBtn.frame = CGRectMake(codeVerticalLine.right, verificationCodeTitleLab.top, codeBorderLine.right - codeVerticalLine.right, verificationCodeTitleLab.height);
    findNoCodeLab.frame = CGRectMake(prefixPhoneLab.left, codeBorderLine.bottom + 13/WIDTH_6_SCALE, [self sizeWithText:@"找不到验证码？请拨打客服电话" maxSize:CGSizeMake(MAXFLOAT, 14/WIDTH_6_SCALE) fontSize:13].width, 14/WIDTH_6_SCALE);
    serveBtn.frame = CGRectMake(findNoCodeLab.right, findNoCodeLab.top, [self sizeWithText:@"400-888-8888" maxSize:CGSizeMake(MAXFLOAT, 14/WIDTH_6_SCALE) fontSize:13].width, findNoCodeLab.height);
    serveBtn.centerY = findNoCodeLab.centerY;
    loginBtn.frame = CGRectMake(weakSelf.view.left + 16/WIDTH_6_SCALE, serveBtn.bottom + 17/WIDTH_6_SCALE, SCREEN_WIDTH - 32/WIDTH_6_SCALE, 40/WIDTH_6_SCALE);
    bottomLine.frame = CGRectMake(headerView.left, loginBtn.bottom + 45/WIDTH_6_SCALE, headerView.width, 1/WIDTH_6_SCALE);
    orLab.frame = CGRectMake(0, 0, 36/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
    orLab.centerX = headerView.centerX;
    orLab.centerY = bottomLine.centerY;
    weChatBtn.frame = CGRectMake(0, bottomLine.bottom + 23/WIDTH_6_SCALE, 40/WIDTH_6_SCALE, 40/WIDTH_6_SCALE);
    weChatBtn.centerX = headerView.centerX;
    weChatLab.frame = CGRectMake(headerView.left, weChatBtn.bottom + 18/WIDTH_6_SCALE, SCREEN_WIDTH, 15/WIDTH_6_SCALE);
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, weChatLab.bottom + 18/WIDTH_6_SCALE);
}
//计算文字的大小
- (CGSize)sizeWithText:(NSString *)text maxSize:(CGSize)maxSize fontSize:(CGFloat)fontSize
{
    //    假设最大CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
    //计算文本的大小
    CGSize nameSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return nameSize;
}
#pragma mark - action
- (void)loginBtnClick:(UIButton *)sender{
    [self phoneNumLogin];
}
- (void)codeBtnClick:(UIButton *)sender{
    if (self.phoneTextField.text.length == 0 || [self.phoneTextField.text isEqualToString:@""] || self.phoneTextField.text == nil) {
        ShowMessage(@"请输入手机号");
        return;
    }
    [self.view endEditing:YES];
    [self sendCodeMessage];//发送验证码
}
- (void)test:(NSTimer *)timmer{
    NSString *str = [NSString stringWithFormat:@"%d后重试",i];
    [self.codeBtn setTitle:str forState:UIControlStateDisabled];
    i--;
    if (i == -1) {
        [timmer invalidate];
        self.codeBtn.enabled = YES;
        [self.codeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        i = 29;
    }
}
@end
